package me.security.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import me.security.base.Data;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;


@Service("userDetailsService")
public class AccountDetailsServiceImpl implements UserDetailsService {

	private final Logger logger = Logger.getLogger("AccountDetailsServiceImpl");
    public AccountDetailsServiceImpl() {
    }
    
    
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		logger.info("[username= " + username + "]");
		if(Strings.isNullOrEmpty(username)){
			logger.info("[username is null or Empty " + "]");
			return null;
		}
		
		String password = obtainUser(username);
		if(Strings.isNullOrEmpty(password)){
			logger.info("[password is null or Empty " + "]");
			return null;
		}
		Collection<GrantedAuthority> grantedAuthorities = obtainGrantedAuthorities(username);
		
		
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;
        
        
        return new org.springframework.security.core.userdetails.User(username, password, enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, grantedAuthorities);
	}


	private Collection<GrantedAuthority> obtainGrantedAuthorities(String username) {
		List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
		String [] roles = Data.accountAndRole.get(username);
		for(String role : roles){
			String [] authorities = Data.roleAndAuthority.get(role);
			for(String authority : authorities){
				GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority);
				result.add(grantedAuthority);
			}
		}
		return result;
	}


	private String obtainUser(String username) {
		
		if(Data.usernameAndPassword.get(username) == null ){
			return null;
		}
		return username;
	}
	
	
	

}
